import { Injectable } from '@nestjs/common';
import { UsersService } from '@/modules/admin/users/users.service'
import { JwtService } from '@nestjs/jwt';
import dayjs from 'dayjs'
import { create } from "svg-captcha";
import { RESPONSE_CODE } from '@/enums/code'

import { aud, expires_date, jti, token_type } from '@/config/jwt'

@Injectable()
export class AuthService {

  constructor(
    private usersService: UsersService,
    private jwtService: JwtService
  ) { }

  async login(username: string, password: string, headers) {
    const user = await this.usersService.getUserByUsername(username, password);
    if (!user || !user.dataValues.status) {
      return null;
    }
    const iat = dayjs().unix();

    const exp = dayjs().add(expires_date, "day").unix();
    const payload = { sub: username, username: user.dataValues.userCode, userId: user.dataValues.userId, iat };

    const access_token = await this.jwtService.signAsync(payload);

    const exp_in = exp - iat;

    return {
      sub: username,
      iss: headers['signal'],
      active: Boolean(user.dataValues.status),
      token_type,
      client_id: aud.join(","),
      access_token: access_token,
      refresh_token: access_token,
      aud: aud,
      license: headers['signal'],
      nbf: iat, //生效日期
      user_id: user.dataValues.userId,
      scope: ["server"],
      exp: exp, //过期时间
      expires_in: exp_in, //过期时间差
      iat: iat, // 签发日期
      jti: jti,
      username: username,
    };
  }

  async logout() {
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null
    }
  }

  async verificationcodeCreate() {
    const captcha = create({
      size: 4,
      ignoreChars: "",
      noise: 2,
      color: true,
      width: 120,
      height: 40,
    })
    return captcha;
  }
}


